import { exec } from 'child_process';
import path from 'path';
import fs from 'fs';
const _path = process.cwd();
export const rule = {
  重启: {
    reg: '^#重启$', //匹配消息正则，命令正则
    priority: 1, //优先级，越小优先度越高
    describe: '重启' //【命令】功能说明
  }
};

export async function 重启(e) {
  if (e.eventType === 'MESSAGE_CREATE') {
    if (
      !e.msg.member.roles.includes('4')
      // && !e.msg.member.roles.includes('5')
    ) {
      let message = {
        content: `<@!${e.msg.author.id}> 无权限`,
        msg_id: e.msg.id
      };

      let { data } = await client.messageApi.postMessage(
        e.msg.channel_id,
        message
      );
      logger.info(data);

      return true;
    }
    let message = {
      content: `<@!${e.msg.author.id}> 重启中...`,
      msg_id: e.msg.id
    };

    let { data } = await client.messageApi.postMessage(
      e.msg.channel_id,
      message
    );
    logger.info(data);

    let bot = {
      重启: true,
      e: e
    };
    fs.mkdirSync(path.join(_path, './resources/bot'), { recursive: true });
    fs.writeFileSync(
      path.join(_path, './resources/bot/重启.json'),
      JSON.stringify(bot, null, 2)
    );

    await exe('npm run start');

    process.exit();
  } else {
    let message = {
      content: `请在子频道发送命令：#重启`,
      msg_id: e.msg.id // 可选，消息id，如果指定则会回复该消息
    };
    const { data } = await client.directMessageApi.postDirectMessage(
      e.msg.guild_id,
      message
    );
    logger.info(data);
    return true;
  }
}

function exe(command) {
  return new Promise((resolve, reject) => {
    exec(command, (err, stdout, stderr) => {
      if (err) {
        logger.error(err);
        process.exit();
      } else {
        resolve(stdout);
      }
    });
  });
}

// 重启判断
let exist = fs.existsSync(path.join(_path, './resources/bot/重启.json'));
if (exist) {
  let data = fs.readFileSync(path.join(_path, './resources/bot/重启.json'));
  let bot = JSON.parse(data.toString());
  if (bot.重启) {
    let e = bot.e;
    let message = {
      content: `<@!${e.msg.author.id}> 重启成功`,
      msg_id: e.msg.id
    };

    client.messageApi
      .postMessage(e.msg.channel_id, message)
      .then(res => {
        logger.info(res);
      })
      .catch(err => {
        logger.error(err);
      });

    logger.info('重启成功');
    fs.unlinkSync(path.join(_path, './resources/bot/重启.json'));
  }
}
